class_name Enemy
extends Unit


@onready var hitbox_component: Area2D = $HitboxComponent
@onready var vision_area: Area2D = $VisionArea



## 与玩家的最小距离，小于此距离时不在跟随玩家
@export var player_distance: float = 50.0
## 群体推力
@export var flock_push: float = 20.0


var _player: Player
# 默认的缩放
var _default_scale: Vector2
# 与玩家最小距离的平方
var _player_distance_square: float
var _can_move: bool = true


func _ready():
	super._ready()
	_default_scale = scale
	hitbox_component.setup(stats.damage)

	_player_distance_square = pow(player_distance, 2)

	await get_tree().process_frame
	_player = Sundry.find_player(get_tree())



func _process(delta: float):
	if not _can_move:
		return
	if not can_move_towards_player():
		return

	look_at_player()
	position += move_direction() * stats.speed * delta



## 判断是否可以跟随至玩家
func can_move_towards_player() -> bool:
	return _player and global_position.distance_squared_to(_player.global_position) > _player_distance_square



## 获取移动方向
func move_direction() -> Vector2:
	if not _player:
		return Vector2.ZERO
	var direction := global_position.direction_to(_player.global_position)
	var has_overlapping := false
	for area: Area2D in vision_area.get_overlapping_areas():
		if area != self:
			has_overlapping = true
			var vec := global_position - area.global_position
			direction += flock_push * vec.normalized() / vec.length()
	if has_overlapping:
		direction = direction.normalized()
	return direction



func look_at_player():
	if not _player:
		return
	if _player.global_position.x > global_position.x:
		scale.x = -_default_scale.x
	else:
		scale.x = _default_scale.x
